import $U from './index.js';
import store from '@/store/index.js'; //需要引入store
const register = async payload => {
	const {
		username,
		password
	} = payload
	try {
		$U.loading()
		const res = await uniCloud.callFunction({
			name: "user",
			data: {
				action: 'register',
				data: {
					username,
					password
				}
			}
		})
		const result = res.result
		if (result.code > 0) {
			$U.notice(result.message || '校验失败')
			return
		}
		$U.refreshUser(result)
		store.commit('user/islogin', true)
		store.commit('user/saveusername', result.userInfo.username)
		$U.notice('注册成功')
		$U.toHomePage()
	} catch (e) {
		$U.notice(e.message || '校验失败')
	} finally {
		$U.hideLoading()
	}
}
const login = async payload => {
	const {
		username,
		password
	} = payload
	try {
		$U.loading()
		const res = await uniCloud.callFunction({
			name: "user",
			data: {
				data: {
					username,
					password
				},
				action: 'login'
			}
		})
		const result = res.result
		if (result.code > 0) {
			$U.notice(result.message || '校验失败')
			return
		}
		$U.refreshUser(result)
		store.commit('user/islogin', true)
		store.commit('user/saveusername', result.userInfo.username)
		$U.notice('登录成功')
		$U.toHomePage()
	} catch (e) {
		$U.notice(e.message || '校验失败')
	} finally {
		$U.hideLoading()
	}

}
const logout = async payload => {
	try {
		$U.loading()
		const res = await uniCloud.callFunction({
			name: "user",
			data: {
				action: 'logout'
			}
		})
		const result = res.result
		if (result.code > 0) {
			$U.notice(result.message || '校验失败')
			return
		}
		uni.removeStorageSync('username')
		uni.removeStorageSync('uni_id_token')
		uni.removeStorageSync('uni_id_token_expired')
		store.commit('user/islogin', false)
		store.commit('user/saveusername', '')
		$U.notice('退出成功')
		$U.toHomePage()
	} catch (e) {
		$U.notice(e.message || '校验失败')
	} finally {
		$U.hideLoading()
	}

}
const checkToken = async () => {
	try {
		$U.loading()
		const res = await uniCloud.callFunction({
			name: "user",
			data: {
				action: 'checkLogin'
			}
		})
		const result = res.result
		// console.log(result)
		if (result.code > 0) {
			 // $U.showModal()
			// $U.notice(result.message || '未登录')
			uni.removeStorageSync('uni_id_token')
			uni.removeStorageSync('uni_id_token_expired')
			uni.removeStorageSync('username')
			store.commit('user/islogin', false)
			return
		}
		$U.refreshUser(result)
		store.commit('user/islogin', true)
		store.commit('user/saveusername', result.userInfo.username)
		$U.notice(`欢迎${result.userInfo.username}回来`)
		// $U.toHomePage()
	} catch (e) {
		$U.notice(e.message || '校验失败')
	} finally {
		$U.hideLoading()
	}

}
export default {
	register,
	login,
	logout,
	checkToken
}
